package com.dede.screensaverhelper.activity

import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.Gravity
import com.dede.screensaverhelper.Config
import com.dede.screensaverhelper.dexFile
import com.dede.screensaverhelper.legalFile
import com.dede.screensaverhelper.util.JavaShellUtil
import org.jetbrains.anko.defaultSharedPreferences
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.toast

/**
 * @author hsh
 * @since 2018/2/2 17:18.
 */
class DreamTempActivity : AppCompatActivity() {

    private val TAG = "DreamTempActivity"

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        if (!isDreaming()) {
            dream()
        }
        window.setGravity(Gravity.LEFT or Gravity.TOP)
        val params = window.attributes
        params.x = 0
        params.y = 0
        params.height = 1
        params.width = 1
//        params.screenBrightness = 0f// to dim
        window.attributes = params
    }

    override fun onResume() {
        super.onResume()
        if (sIsDreaming) {
            sIsDreaming = false
            finish()
        }
    }

    override fun onPause() {
        super.onPause()
        val keepScreenOn = defaultSharedPreferences.getBoolean(Config.KEEP_SCREEN_ON, true)
        Log.i(TAG, "sIsDreaming: $sIsDreaming  keep: $keepScreenOn")
        if (sIsDreaming && keepScreenOn) {
            Log.i(TAG, "onPause: ")
        }
    }

    companion object {
        private var sIsDreaming = false

        fun isDreaming() = sIsDreaming
    }

    private fun dream() {
        val file = dexFile()
        if (!file.legalFile()) {
            toast("文件未找到")
            return
        }
        val setClassPath = "export CLASSPATH=${file.absolutePath}"
        val exec = "exec app_process ${file.parentFile.absolutePath} ${Config.mainClass}"
        Log.i("test", setClassPath)
        Log.i("test", exec)
        doAsync {
            val result = JavaShellUtil.execCommand(true, setClassPath, exec)
            Log.i("test", result.toString())
            if ("end" != result.responseMsg) {
                runOnUiThread {
                    toast("打开失败")
                }
            } else {
                sIsDreaming = true
            }
        }
    }
}